package zut.wework.controller;

import ch.qos.logback.core.util.TimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import zut.wework.api.WorkWXAPI;
import zut.wework.api.WxApi;
import zut.wework.entity.*;
import zut.wework.mapper.WxDeptMapper;
import zut.wework.mapper.ZsjBzksMapper;
import zut.wework.service.impl.ZsjBzksServiceImpl;
import zut.wework.utils.HttpClientUtil;
import zut.wework.utils.JsonUtil;
import zut.wework.utils.WXAPIUtil;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Controller
@Slf4j
@RequestMapping("/wework/users")
public class WxUserController {

    @Autowired
    private ZsjBzksMapper zsjBzksMapper;
    @Autowired
    private WxDeptMapper wxDeptMapper;
    @Autowired
    private WxApi wxApi;

    @RequestMapping("index")
    public String login() {
        return "/wx/login";
    }

    /**
     * 注册添加手机号
     *
     * @param phone
     * @param session
     * @param modelAndView
     * @return
     */
    @PostMapping("register")
    public ModelAndView register(String phone, HttpSession session, ModelAndView modelAndView) {
        ZsjBzks userInfo = (ZsjBzks) session.getAttribute("userInfo");
        if (userInfo == null) {
            modelAndView.setViewName("wx/msg");
            modelAndView.addObject("msg", new MsgDomain(-1,
                    "错误提示", "非法请求！"));
        } else {
            Map<String, Object> map = new HashMap<String, Object>() {
                {
                    put("userid", userInfo.getXh());
                    put("name", userInfo.getXm());
                    put("mobile", phone);
//                    put("order", Arrays.asList(10000 - userInfo.get()));
                    put("to_invite", false);
                }
            };

            String year = userInfo.getXh().substring(0, 4);
            Integer px = wxDeptMapper.selectOne(new QueryWrapper<WxDept>().eq("name", year + "级")).getPx();
            WxDept Dept = wxDeptMapper.selectDept(new WxDept(null, null, null, null, px, userInfo.getBh(), null));
            int wxId = 0;
            if (Dept != null) {
                wxId = Dept.getId();
            } else {
                log.error("获取部门错误！");
            }
            map.put("department", Arrays.asList(wxId));
            log.info("注册信息:{}", JsonUtil.toJson(map));
            if (wxApi.createUser(map)) {
                userInfo.setTelphone(phone);
                if (zsjBzksMapper.update(userInfo, new QueryWrapper<ZsjBzks>().eq("xh", userInfo.getXh())) == 1) {
                    log.info("更新成功{}", userInfo);
                    modelAndView.setViewName("wx/register_success");
                } else {
                    log.error("更新失败{}", userInfo);
                    modelAndView.setViewName("wx/msg");
                    modelAndView.addObject("msg", new MsgDomain(-1,
                            "错误提示", "更新失败"));
                }
            } else {
                log.error("创建用户失败！");
                modelAndView.setViewName("wx/msg");
                modelAndView.addObject("msg", new MsgDomain(-1,
                        "错误提示", "创建用户失败"));
            }


        }
        return modelAndView;
    }

    /**
     * 新人入队？？
     *
     * @param xh
     * @param pwd
     * @param session
     * @param modelAndView
     * @return
     */
    @PostMapping("login")
    public ModelAndView login(@RequestParam(value = "xh") String xh, @RequestParam(value = "pwd") String pwd, HttpSession session, ModelAndView modelAndView) {
        ZsjBzks zsjBzks = zsjBzksMapper.selectOne(new QueryWrapper<ZsjBzks>().eq("xh", xh));
        session.setAttribute("userInfo", zsjBzks);
        if (zsjBzks != null) {
            String password = zsjBzks.getCsrq().substring(8) + zsjBzks.getSfzh().substring(12);
            log.info("password:{}", password);
            if (pwd.equals(password)) {
                modelAndView.setViewName("wx/register");
                modelAndView.addObject("xh", xh);
                modelAndView.addObject("name", zsjBzks.getXm());
                return modelAndView;
            } else {
                modelAndView.setViewName("wx/msg");
                modelAndView.addObject("msg", new MsgDomain(-1, "错误提示", "密码错误"));
                return modelAndView;
            }
        } else {
            modelAndView.setViewName("wx/msg");
            modelAndView.addObject("msg", new MsgDomain(-1, "错误提示", "用户不存在！"));
            return modelAndView;
        }

    }

//  https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxCorpId&redirect_uri=http%3a%2f%2fapi.3dept.com%2fcgi-bin%2fquery%3faction%3dget&response_type=code&scope=snsapi_base&state=#wechat_redirect
    @RequestMapping("authTest")
    @ResponseBody
    public Result test(@RequestParam(value = "code") String code) {
        //判断url 合法性
        log.info("code:{}", code);
        String getUserInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + wxApi.getKeBiaoAccessToken() + "&code=" + code;
        Map<String, Object> userInfo = new HashMap<>();

        //发送请求获得用户信息
        userInfo = JsonUtil.toMap(HttpClientUtil.get(getUserInfoUrl));
        log.info("userInfo:{}", userInfo);
        //验证用户信息
        return Result.success("ok");
    }


}
